package cn.wen233.orderconsumer.infrustructure.fallback;

import cn.wen233.common.api.R;
import cn.wen233.common.infrustructure.exception.BaseException;
import cn.wen233.domain.Order;
import cn.wen233.orderconsumer.infrustructure.feign.OrderFeign;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.hystrix.FallbackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 回退工厂
 *
 * @author wenei
 * @date 2021-06-05 17:00
 */
@Component
public class OrderFeignFallbackFactory implements FallbackFactory<OrderFeign> {

    private static final Logger log = LoggerFactory.getLogger(OrderFeignFallbackFactory.class);

    private final ObjectMapper mapper;

    public OrderFeignFallbackFactory(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    /**
     * 获取到FeignConfiguration中解码时的错误
     * @param throwable
     * @return
     */
    @Override
    public OrderFeign create(Throwable throwable) {
        log.warn("回退工厂中的异常信息：" + throwable.toString());
        OrderFeign orderFeign = new OrderFeign() {
            @Override
            public R<Order> getOrder(String id) {
                // 业务逻辑处理
                throw new BaseException("调用getOder服务出错");
            }
        };
//        return (x) -> R.success(Order.builder().address("假的").description("回退工厂建立的").build());
//        throw new BaseException(mapper.convertValue(throwable.toString(), JsonNode.class).get("message").toString());
        return orderFeign;
    }
}
